package priv.blackbibo.application.activity;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import androidx.constraintlayout.widget.ConstraintLayout;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import priv.blackbibo.application.R;
import priv.blackbibo.application.service.MusicService;
import priv.blackbibo.application.service.SongListLoadService;

public class MusicActivity extends BaseActivity implements AdapterView.OnItemClickListener {

    private String TAG = "MusicActivity";

    private ListView listView = null;

    private List<Map<String, String>> list = new LinkedList<>();

    private SongListAdapter songListAdapter = null;

    private Button playBtn = null;

    private Button nextBtn = null;

    private Button restoreBtn = null;

    private Handler handler = new Handler();

    private TextView playingMusicName = null;

    private View currentPlayItem = null;

    private ProgressBar progressBar = null;

    private SongloadFinishedReceiver songloadFinishedReceiver = null;

    public static final int ACTION_START = 1;
    public static final int ACTION_PAUSE = 2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_music_simple);

        if (this.checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            this.requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE},1);
        }


        int lastAction = getSharedPreferences(getString(R.string.key_configuration), MODE_PRIVATE).getInt(MusicService.STATE_KEY, -1);
        initActivity(lastAction);
        checkState(lastAction);
        registerReceiver();

    }

    RefreshViewReceiver refreshViewReceiver = new RefreshViewReceiver();
    private void registerReceiver() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("priv.blackbibo.application.activity.MusicActivity.RefreshViewReceiver");
        registerReceiver(refreshViewReceiver, intentFilter);
    }

    private void unregisterReceiver() {
        unregisterReceiver(refreshViewReceiver);
    }

    private void checkState(int lastAction) {
        int action = getIntent().getIntExtra("action",-1);
        switch (action) {
            case ACTION_START:
                if (lastAction == MusicService.ACTION_START || lastAction == MusicService.ACTION_RESTART) {
//                    pause();
                } else if (lastAction == -1) {
                    nextPlay();
                } else if (lastAction == MusicService.ACTION_STOP) {
                    nextPlay();
                } else if (lastAction == MusicService.ACTION_PAUSE) {
                    restart();
                }
                break;
            case ACTION_PAUSE:
                if (lastAction == MusicService.ACTION_START || lastAction == MusicService.ACTION_RESTART) {
                    pause();
                } else if (lastAction == -1) {
//                    nextPlay();
                } else if (lastAction == MusicService.ACTION_STOP) {
//                    nextPlay();
                } else if (lastAction == MusicService.ACTION_PAUSE) {
//                    restart();
                }
                break;
                default:
                    onlyCheck();
        }
    }

    private void initActivity(int lastAction) {
        playingMusicName = findViewById(R.id.music_name);
        progressBar = findViewById(R.id.progressBar);
        listView = findViewById(R.id.list);
        playBtn = findViewById(R.id.play_btn);
        playBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int lastAction = getSharedPreferences(getString(R.string.key_configuration), MODE_PRIVATE).getInt(MusicService.STATE_KEY, -1);
                if (lastAction == MusicService.ACTION_START || lastAction == MusicService.ACTION_RESTART) {
                    pause();
                } else if (lastAction == -1) {
                    nextPlay();
                } else if (lastAction == MusicService.ACTION_STOP) {
                    nextPlay();
                } else if (lastAction == MusicService.ACTION_PAUSE) {
                    restart();
                }
            }
        });
        if (lastAction == MusicService.ACTION_START || lastAction == MusicService.ACTION_RESTART) {
            playBtn.setBackgroundResource(R.drawable.ic_stop);
        } else {
            playBtn.setBackgroundResource(R.drawable.ic_start);
        }

        nextBtn = findViewById(R.id.play_next);
        nextBtn.setOnClickListener((v)->{
            nextPlay();
        });

        restoreBtn = findViewById(R.id.refresh);
        restoreBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                loading();
                startLoadTask();

            }
        });

        list.addAll(readCache());

        String[] from = new String[]{"index","path","name"};
        int[] to = new int[]{R.id.index,R.id.path,R.id.name};

        songListAdapter = new SongListAdapter(this, list, R.layout.song_item,from,to);
        listView.setAdapter(songListAdapter);
        listView.setOnItemClickListener(this);
    }

    private void startLoadTask() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(SongListLoadService.ACTION);
        songloadFinishedReceiver = new SongloadFinishedReceiver();
        registerReceiver(songloadFinishedReceiver, intentFilter);

        /**
         * 后台启动扫描任务
         */
        Intent intent = new Intent(getApplicationContext(), SongListLoadService.class);
        startService(intent);
    }

    public void loading(){
        View shadow = findViewById(R.id.shadow);
        shadow.setVisibility(View.VISIBLE);
        shadow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
    }

    public void unloading(){
        View shadow = findViewById(R.id.shadow);
        shadow.setVisibility(View.GONE);
    }

    public int getCurrentPosition(){
        SharedPreferences sharedPreferences = getSharedPreferences();
        return sharedPreferences.getInt(MusicService.POSITION_KEY, -1);
    }

    public void setCurrentPosition(int currentPosition){
        SharedPreferences sharedPreferences = getSharedPreferences();
        sharedPreferences.edit().putInt(MusicService.POSITION_KEY, currentPosition).commit();
    }

    private SharedPreferences getSharedPreferences() {
        return getSharedPreferences(getString(R.string.key_configuration), MODE_PRIVATE);
    }

    private void refreshView(){
        if (list == null || list.size() == 0) {
            return;
        }
        int newPosition = getCurrentPosition();
        int lastPos = listView.getLastVisiblePosition();
        int firtPos = listView.getFirstVisiblePosition();
        int step = 0;
        double relative = (newPosition - firtPos) * 1.0 / (lastPos - firtPos);
        Log.d(TAG, "onCreate: " + relative);
        if ( relative > 0.5 ) {
            step = (lastPos - firtPos) / 2;
            listView.smoothScrollToPosition(newPosition + step);
        } else if (relative < 0) {
            listView.smoothScrollToPosition(newPosition);
        }

        for (int i = 0; i < list.size(); i++) {
            Map<String, String> newItem = list.get(i);
            if (i == newPosition) {
                newItem.put("selected", "true");
            }else {
                newItem.put("selected", "false");
            }
        }

        View view = getViewByPosition(newPosition, listView);
        /**
         * 选择后的
         */
        currentPlayItem = view;
        LinearLayout item = currentPlayItem.findViewById(R.id.item);
        item.setBackgroundResource(R.drawable.round_song_selected_shape);
        TextView textView = item.findViewById(R.id.name);
        String musicName = textView.getText().toString();
        textView.setTextColor(getColor(R.color.text_common_white));
        playingMusicName.setText(musicName);
        songListAdapter.notifyDataSetChanged();
    }

    public void nextPlay() {
        int position = getCurrentPosition();
        position++;
        setCurrentPosition(position);
        Intent intent = new Intent(this, MusicService.class);
        intent.putExtra("action", MusicService.ACTION_NEXT);
        startService(intent);
    }

    /**
     * 通过位置找到ListView中的某个item的View
     * @param pos
     * @param listView
     * @return
     */
    public View getViewByPosition(int pos, ListView listView) {
        int firstListItemPosition = listView.getFirstVisiblePosition();
        int lastListItemPosition = firstListItemPosition
                + listView.getChildCount() - 1;

        if (pos < firstListItemPosition || pos > lastListItemPosition) {
            //不在可视范围内
            return listView.getAdapter().getView(pos, null, listView);
        } else {
            final int childIndex = pos - firstListItemPosition;
            return listView.getChildAt(childIndex);
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        setCurrentPosition(position);
        play(null);
    }

    private static final String cacheFileName = "songs";
    public List<Map<String,String>> readCache(){
        Log.d(TAG, "readCache: load xml");
        File folder = getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS);
        File file = new File(folder.getAbsolutePath() + "/" +cacheFileName+ ".xml");
        if (file.exists()){
            try {
                DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
                DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder();
                Document document = builder.parse(file);
                NodeList songs = document.getElementsByTagName("song");
                List<Map<String, String>> list = new LinkedList<>();
                for (int i = 0; i < songs.getLength(); i++) {
                    Node node = songs.item(i);
                    NodeList song = node.getChildNodes();
                    Map<String, String> songMap = new HashMap<>();
                    for (int j = 0; j < song.getLength(); j++) {
                        Node son = song.item(j);
                        if (son.getNodeName().equals("path")) {
                            songMap.put("path", son.getTextContent());
                        } else if (son.getNodeName().equals("name")) {
                            songMap.put("name", son.getTextContent());
                        } else if (son.getNodeName().equals("index")) {
                            songMap.put("index", son.getTextContent());
                        }
                    }
                    list.add(songMap);
                }
                return list;
            } catch (ParserConfigurationException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (SAXException e) {
                e.printStackTrace();
            }
            return  new LinkedList<>();
        }else{
            return  new LinkedList<>();
        }
    }



    private void onlyCheck() {

        Intent intent = new Intent(this, MusicService.class);
        intent.putExtra("action", MusicService.ACTION_CHECK);
        startService(intent);

        handler.post(() -> {
            playBtn.setBackgroundResource(R.drawable.ic_stop);
        });
    }

    private void restart() {

        Intent intent = new Intent(this, MusicService.class);
        intent.putExtra("action", MusicService.ACTION_RESTART);
        startService(intent);

        handler.post(() -> {
            playBtn.setBackgroundResource(R.drawable.ic_stop);
        });
    }

    private void pause() {
        Intent intent = new Intent(this, MusicService.class);
        intent.putExtra("action", MusicService.ACTION_PAUSE);
        startService(intent);

        handler.post(() -> {
            playBtn.setBackgroundResource(R.drawable.ic_start);
        });
    }

    private void play(String source) {
        Intent intent = new Intent(this, MusicService.class);
        intent.putExtra("action", MusicService.ACTION_START);
        intent.putExtra("source", source);
        startService(intent);
    }

    class SongListAdapter extends SimpleAdapter {
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (list == null || list.size() ==0 ) {
                return null;
            }
            Map<String,String> params  = list.get(position);
            String selected = params.get("selected");
            View view = super.getView(position, null, parent);
            TextView nameView = view.findViewById(R.id.name);
            if (selected != null && selected.equals("true")) {
                view.setBackgroundResource(R.drawable.round_song_selected_shape);
                nameView.setTextColor(getColor(R.color.text_common_white));
            }else {
                view.setBackgroundResource(R.drawable.round_song_unselected_shape);
                nameView.setTextColor(getColor(R.color.text_common_drark));
            }
            return view;
        }

        public SongListAdapter(Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to) {
            super(context,data,resource,from,to);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver();
    }

    class RefreshViewReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.d(TAG, "onReceive: received");
            refreshView();
        }
    }

    class SongloadFinishedReceiver extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
            Toast.makeText(getApplicationContext(), "音乐加载完成",Toast.LENGTH_SHORT).show();
            list.clear();
            list.addAll(readCache());
            refreshView();
            unloading();
            unregisterReceiver(songloadFinishedReceiver);
        }
    }

}
